using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace Smarly.Bussines
{
	public class Serializer
	{
		public static string Diserialize<T>(T obj) where T : class
		{
			if (obj == null)
				return null;

			MemoryStream ms = new MemoryStream();
			using (XmlWriter writer = XmlWriter.Create(ms, new XmlWriterSettings { Indent = false, NewLineHandling = NewLineHandling.None, OmitXmlDeclaration = true }))
			{
				XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
				ns.Add(string.Empty, string.Empty);

				XmlSerializer x = new XmlSerializer(typeof(T));
				x.Serialize(writer, obj, ns);

				return Encoding.UTF8.GetString(ms.ToArray());
			}
		}

		public static T Serialize<T>(string str) where T : class
		{
			if (string.IsNullOrWhiteSpace(str))
				return null;

			using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(str)))
			{
				XmlSerializer x = new XmlSerializer(typeof(T));
				return (T)x.Deserialize(ms);
			}
		}
	}
}